package lumingweihua.future.cn.lumingweihua.home.cheyuan;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import lumingweihua.future.cn.baselibgxh.adapter.BaseViewHolder;
import lumingweihua.future.cn.baselibgxh.adapter.CommonAdapter;
import lumingweihua.future.cn.baselibgxh.adapter.MyViewPagerAdapter;
import lumingweihua.future.cn.baselibgxh.base.BaseFragment;
import lumingweihua.future.cn.baselibgxh.base.MyApplication;
import lumingweihua.future.cn.baselibgxh.network.AbstractRequest;
import lumingweihua.future.cn.baselibgxh.network.BeanRequest;
import lumingweihua.future.cn.baselibgxh.network.NetworkManager;
import lumingweihua.future.cn.baselibgxh.network.PureListRequest;
import lumingweihua.future.cn.baselibgxh.network.ReqTag;
import lumingweihua.future.cn.baselibgxh.network.entity.MamaHaoServerError;
import lumingweihua.future.cn.baselibgxh.utils.CommonUtils;
import lumingweihua.future.cn.baselibgxh.utils.ImageUtils;
import lumingweihua.future.cn.baselibgxh.utils.PageLoadUtil;
import lumingweihua.future.cn.baselibgxh.widget.FooterListViewUtil;
import lumingweihua.future.cn.baselibgxh.widget.MarqueeView;
import lumingweihua.future.cn.baselibgxh.widget.MyListView;
import lumingweihua.future.cn.lumingweihua.MainActivity;
import lumingweihua.future.cn.lumingweihua.R;
import lumingweihua.future.cn.lumingweihua.WebViewActivity;
import lumingweihua.future.cn.lumingweihua.home.domain.CheyuanData;
import lumingweihua.future.cn.lumingweihua.home.domain.StockData;
import lumingweihua.future.cn.lumingweihua.person.LoginActivity;
import lumingweihua.future.cn.lumingweihua.person.domain.Banner;
import lumingweihua.future.cn.lumingweihua.widget.CheyuanSortNaviBar;

/**
 * Created by Administrator on 2018/3/2.
 */

public class CheyuanFragment extends BaseFragment  implements FooterListViewUtil.FooterScrollListener,AdapterView.OnItemClickListener {
    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container) {
        return View.inflate(getActivity(), R.layout.fragment_cheyuan, null);
    }

    /**
     * 排序导航栏
     */
    private CheyuanSortNaviBar naviBar;
    private CheyuanSortNaviBar naviBarFloat;
    private PtrClassicFrameLayout mPtrFrame;
    protected MyListView listview;
    protected View headerView;
    protected List<CheyuanData> datas;
    private CommonAdapter<CheyuanData> adapter;
    private int currentItemPos;

    /**
     * 分页加载工具
     */
    protected PageLoadUtil pageLoadUtil;
    //开始地点选择器
    private OptionsPickerView startCityPickerView;
    //结束地点选择器
    private OptionsPickerView endCityPickerView;
    //装货时间
    private OptionsPickerView timePickerView;
    private List<String> times;

    @Override
    protected void onFirstUserVisible() {
        // TODO Auto-generated method stub
        super.onFirstUserVisible();
        listview = (MyListView) findView(R.id.listview);
        mPtrFrame = (PtrClassicFrameLayout) findView(R.id.list_view_with_empty_view_fragment_ptr_frame);

        mPtrFrame.setLastUpdateTimeRelateObject(this);
        mPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, listview, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                requestStocks();
                refreshDatas(true,false);
            }
        });
        // the following are default settings
        mPtrFrame.setResistance(1.7f);
        mPtrFrame.setRatioOfHeaderHeightToRefresh(1.2f);
        mPtrFrame.setDurationToClose(200);
        mPtrFrame.setDurationToCloseHeader(1000);
        mPtrFrame.setPullToRefresh(false);
        mPtrFrame.setKeepHeaderWhenRefresh(true);
        mPtrFrame.setHeaderView(View.inflate(context, R.layout.refresh_top_item2, null));


        headerView = View.inflate(baseActivity, R.layout.cheyuan_header_view, null);
        //导航栏
        naviBar = (CheyuanSortNaviBar) headerView.findViewById(R.id.sort_navi_bar);
        //导航变化监听
        naviBar.setOnNaviBarChangeListener(new CheyuanSortNaviBar.OnNaviBarChangeListener() {

            @Override
            public void onNaviChanged(int lastNaviPostion,
                                      int currentNaviPostion) {
                // TODO Auto-generated method stub
                naviBarFloat.changeNavi(currentNaviPostion, false);
                showPickView(currentNaviPostion);
//                refreshDatas(true,true);
            }

            @Override
            public void onArrowChanged(int naviPosition, int arrowDirection) {
                // TODO Auto-generated method stub
            }
        });

        listview.addHeaderView(headerView);
        listview.setOnMyScrollListener(this, true, true);

        datas = new ArrayList<>();

        adapter = new CommonAdapter<CheyuanData>(baseActivity, datas, R.layout.item_cheyuan_list) {

            @Override
            public void convert(BaseViewHolder holder, CheyuanData itemData,
                                int position, ViewGroup parent) {
                // TODO Auto-generated method stub
                holder.setImageByUrl(R.id.iv_icon, itemData.getImg_path(), ImageUtils.imgOptionsSmall);
                holder.setText(R.id.tv_city, itemData.getStartCity2());
                holder.setText(R.id.tv_end_city, itemData.getEndCity2());
                holder.setText(R.id.tv_address, itemData.getAddress());
                holder.setText(R.id.tv_time, itemData.getLinkname()+"   装货时间:"+itemData.getTime());
                holder.setText(R.id.tv_carnum, itemData.getCarnum());

                holder.getView(R.id.iv_luming).setVisibility(itemData.getIs_plat()?View.VISIBLE:View.GONE);
                holder.getView(R.id.tv_jiaji).setVisibility(itemData.getJiaji()?View.VISIBLE:View.GONE);

//                RelativeLayout rl_p = holder.getView(R.id.rl_p);
//                try {
//                    if(itemData.getTime().contains("月") && itemData.getTime().contains("日")){
//                        int m = Integer.valueOf(itemData.getTime().substring(0,itemData.getTime().indexOf("月")));
//                        int d = Integer.valueOf(itemData.getTime().substring(itemData.getTime().indexOf("月")+1,itemData.getTime().indexOf("日")));
//
//                        int tm = Calendar.getInstance().get(Calendar.MONTH)+1;
//                        int td = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
//                        if(tm == m && d == td){
//                            //今天
//                            rl_p.setBackgroundColor(Color.parseColor("#E5F7E3"));
//                        }else if(tm == m && d == td-1){
//                            //昨天
//                            rl_p.setBackgroundColor(Color.parseColor("#F5F7E3"));
//                        }else{
//                            //
//                            rl_p.setBackgroundColor(Color.parseColor("#ffffff"));
//                        }
//                    }else
//                        rl_p.setBackgroundColor(Color.parseColor("#ffffff"));
//                } catch (Exception e) {
//                    // TODO: handle exception
//                }

            }
        };

        listview.setAdapter(adapter);
        listview.setOnItemClickListener(this);

        pageLoadUtil = new PageLoadUtil(20);

        naviBarFloat = (CheyuanSortNaviBar) findView(R.id.sort_navi_bar_float);
        //添加监听
        naviBarFloat.setOnNaviBarChangeListener(new CheyuanSortNaviBar.OnNaviBarChangeListener() {

            @Override
            public void onNaviChanged(int lastNaviPostion,
                                      int currentNaviPostion) {
                // TODO Auto-generated method stub
                naviBar.changeNavi(currentNaviPostion, false);
                showPickView(currentNaviPostion);
//                refreshDatas(true,true);
            }

            @Override
            public void onArrowChanged(int naviPosition, int arrowDirection) {
                // TODO Auto-generated method stub
            }
        });

        requestBanners();
        refreshDatas(true,true);
        requestStocks();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
    }
    private String origin;
    private String destination;
    private String data = "1000";

    private void showPickView(int currentNaviPostion){
        switch (currentNaviPostion){
            case 0:
                //开始地点
                if(startCityPickerView == null){

                    if(MainActivity.instance.provinces==null || MainActivity.instance.citys==null)
                        return;

                    startCityPickerView = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int options2, int options3, View v) {
//                            startTimes[0] = months.get(options1);
//                            startTimes[1] = hours.get(options1).get(options2);
//                            startTimes[2] = minutes.get(options1).get(options2).get(options3);
                            String city = MainActivity.instance.citys.get(options1).get(options2);
                            origin = MainActivity.instance.provinces.get(options1)+city;
                            naviBar.navi_bar_tvs[0].setText(city);
                            naviBarFloat.navi_bar_tvs[0].setText(city);
                            refreshDatas(true,true);
                        }
                    }).build();
                    startCityPickerView.setPicker(MainActivity.instance.provinces,MainActivity.instance.citys,null);
                    int p1 = MainActivity.instance.provinces.indexOf(MainActivity.instance.provinceName);
                    int p2 = MainActivity.instance.citys.get(p1).indexOf(MainActivity.instance.cityName);
                    startCityPickerView.setSelectOptions(p1,p2);
                }
                startCityPickerView.show();
                break;
            case 1:
                //结束地点
                //开始地点
                if(endCityPickerView == null){

                    if(MainActivity.instance.provinces==null || MainActivity.instance.citys==null)
                        return;

                    endCityPickerView = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int options2, int options3, View v) {
                            String city = MainActivity.instance.citys.get(options1).get(options2);
                            destination = MainActivity.instance.provinces.get(options1)+city;
                            naviBar.navi_bar_tvs[1].setText(city);
                            naviBarFloat.navi_bar_tvs[1].setText(city);
                            refreshDatas(true,true);
                        }
                    }).build();
                    endCityPickerView.setPicker(MainActivity.instance.provinces,MainActivity.instance.citys,null);
                }
                endCityPickerView.show();
                break;
            case 2:
                //装货时间
                if(timePickerView == null){
                    times = new ArrayList<>();
                    times.add("不限");
                    times.add("一天内");
                    times.add("两天内");
                    times.add("三天内");
                    timePickerView  = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int options2, int options3, View v) {
                            switch (options1) {
                                case 0:
                                    data = "1000";
                                    break;
                                case 1:
                                    data = "1";
                                    break;
                                case 2:
                                    data = "2";
                                    break;
                                case 3:
                                    data = "3";
                                    break;

                                default:
                                    break;
                            }
                            naviBar.navi_bar_tvs[2].setText(times.get(options1));
                            naviBarFloat.navi_bar_tvs[2].setText(times.get(options1));
                            refreshDatas(true,true);
                        }
                    }).build();
                    timePickerView.setPicker(times,null);
                }
                timePickerView.show();
                break;
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        // TODO Auto-generated method stub
        // 去详情
        if(!MyApplication.getInstance().isUserLogin()){
            baseActivity.jumpToNextActivity(LoginActivity.class,false);
            return;
        }
        currentItemPos = position-1;
        startActivityForResult(new Intent(context, CheyuanDetailActivity.class)
                .putExtra("id", datas.get(position-1).getId())
                .putExtra("isMine", false)
                ,101);
    }

    private ViewPager vp_home_banner;
    private int bannerCurrent = 0;// banner
    private int bannerSize;
    private boolean isLoopTopPic;//循环标志位
    /**
     * 设置顶部轮播图
     */
    protected void setBanners(final List<Banner> banners){
        vp_home_banner=(ViewPager) headerView.findViewById(R.id.vp_banners);

        if(banners==null || banners.size()<=0){
            vp_home_banner.setVisibility(View.GONE);
            return;
        }

        bannerSize=banners.size();
        if(bannerSize==2)
            banners.addAll(banners);

        //一张图片时不循环
        isLoopTopPic = bannerSize==1?false:true;
        if(isLoopTopPic)
            initHotShopDot(0, bannerSize, Integer.MAX_VALUE);

        List<View > viewList=new ArrayList<View>();
        for (int i = 0; i < banners.size(); i++) {
            Banner banner=banners.get(i);
            ImageView iv=new ImageView(context);
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            iv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, CommonUtils.dip2px(context, 180)));
            ImageLoader.getInstance().displayImage(banner.getImg_url(), iv,ImageUtils.imgOptionsSmall);
            viewList.add(iv);
            iv.setTag(i);
            iv.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    try {
                        Banner bn = banners.get((int)v.getTag());
                        if(!TextUtils.isEmpty(bn.getContent())){
                            startActivity(new Intent(context, WebViewActivity.class).putExtra("url", bn.getContent()));
                        }
//                        else if(!TextUtils.isEmpty(bn.getTarget_url())){
//                            startActivity(new Intent(context, WebViewActivity.class).putExtra("url", bn.getTarget_url()));
//                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                    }

                }
            });
        }

        MyViewPagerAdapter homeBannerAdapter=new MyViewPagerAdapter(viewList);
        if(isLoopTopPic)
            homeBannerAdapter.setSize(Integer.MAX_VALUE);
        else
            homeBannerAdapter.setSize(1);

        vp_home_banner.setAdapter(homeBannerAdapter);

        vp_home_banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                bannerCurrent = arg0;
                updataDot(arg0%bannerSize);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });

        startBannerTimer();
    }

    private View[] dots;
    /**
     * banner小点
     * @param position
     */
    private void initHotShopDot(int position, int size,int maxSize) {
        LinearLayout layout = (LinearLayout) headerView.findViewById(R.id.dot_views);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                CommonUtils.dip2px(context, 6), CommonUtils.dip2px(context, 6));
        params.setMargins(CommonUtils.dip2px(context, 4), 0,
                CommonUtils.dip2px(context, 4), 0);
        dots = new View[size];
        // 先清后加
//        layout.removeAllViews();
        for (int i = 0; i < size && i < maxSize; i++) {
            View dot = new View(context);
            dot.setLayoutParams(params);
            dots[i] = dot;
            layout.addView(dot);
        }
        for (int i = 0; i < dots.length; i++) {
            if (i == position%dots.length) {
                dots[i].setBackgroundResource(R.drawable.dot_red_7);
            } else {
                dots[i].setBackgroundResource(R.drawable.dot_gray_7);
            }
        }
    }

    private int lastPos;
    private void updataDot(int pos){
        dots[lastPos].setBackgroundResource(R.drawable.dot_gray_7);
        dots[pos].setBackgroundResource(R.drawable.dot_red_7);
        lastPos = pos;
    }

    private Timer timer;
    private void startBannerTimer(){
        if (timer == null) {
            timer = new Timer();
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    bannerCurrent++;
                    if(isLoopTopPic){
                        baseActivity.runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                vp_home_banner.setCurrentItem(bannerCurrent);
                            }
                        });
                    }

                }
            }, 5000, 5000);
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private int[] location=new int[2];
    private int statusHeight = 0;// 状态栏高度
    private int titlebarHeight = 0;// titleBar的高度

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {

        if(naviBar == null || naviBarFloat == null)
            return;
        // navibar浮起控制
        naviBar.getLocationOnScreen(location);

        if (titlebarHeight == 0) {
            statusHeight = CommonUtils.getStatusHeight(getActivity());
            titlebarHeight = CommonUtils.dip2px(context,40);
        }

        if (location[1] <= statusHeight + titlebarHeight) {
            if (naviBarFloat.getVisibility() == View.GONE) {
                naviBarFloat.setVisibility(View.VISIBLE);
            }
        }else if(naviBarFloat.getVisibility() == View.VISIBLE)
            naviBarFloat.setVisibility(View.GONE);

    }

    @Override
    public void onSrollToBottom() {
        // TODO Auto-generated method stub
        refreshDatas(false,false);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // TODO Auto-generated method stub

    }

    public void refreshDatas(boolean isRefresh,boolean isShowProgress){
        if(isAdded() && pageLoadUtil!=null){
            pageLoadUtil.updataPage(isRefresh);
            if (isRefresh && isShowProgress)
                baseActivity.showProgressBar(this);
            requestGoodsDatas(pageLoadUtil.getCurrentPage(),pageLoadUtil.getPageSize());
        }
    }

    protected void handleDatas(List<CheyuanData> newDatas) {
        baseActivity.hideProgressBar(this);
        //处理数据
        pageLoadUtil.handleDatas(datas, newDatas);

        //处理footerView
        if(pageLoadUtil.judgeHasMoreData(newDatas))
            listview.setFooterState(FooterListViewUtil.FOOTER_STATE_LOAD_FINISH);
        else
            listview.setFooterState(FooterListViewUtil.FOOTER_STATE_NO_MORE_DATA);

        adapter.notifyDataSetChanged();
    }

    /** 请求标识 **/
    private final String REQUEST_TAG = "CheyuanFragment";
    private final int REQUEST_GOODS_DATAS = 0;
    private final int REQUEST_BANNER = 1;
    private final int REQUEST_STOCKS = 3;

    protected void requestGoodsDatas(int currentPage, int pageSize) {
        // TODO Auto-generated method stub
        PureListRequest<CheyuanData, MamaHaoServerError> req = new PureListRequest<>(
                context,
                "",
                this,
                CheyuanData.class);

        req.setParam("apiCode", "_homepage_car_001");
        req.setParam("userToken", MyApplication.getInstance().getUserToken());
        req.setParam("page", String.valueOf(currentPage));
        req.setParam("size", String.valueOf(pageSize));

        if(!"全部全部".equals(origin))
            req.setParam("origin", origin);
        if(!"全部全部".equals(destination))
            req.setParam("destination", destination);

        req.setParam("data", data);

        //获取token
        String token = NetworkManager.getInstance().getPostToken(req.getParam());
        req.setParam("token", token);

        baseActivity.addRequestQueue(req, REQUEST_GOODS_DATAS, new ReqTag.Builder().handleSimpleRes(true).tag(REQUEST_TAG));

    }

    protected void requestBanners() {
        // TODO Auto-generated method stub
        PureListRequest<Banner, MamaHaoServerError> req = new PureListRequest<>(
                context,
                "",
                this,
                Banner.class);

        req.setParam("apiCode", "_banner_001");

        //获取token
        String token = NetworkManager.getInstance().getPostToken(req.getParam());
        req.setParam("token", token);

        baseActivity.addRequestQueue(req, REQUEST_BANNER, new ReqTag.Builder().tag(REQUEST_TAG));

    }

    private void requestStocks() {
        // TODO Auto-generated method stub
        BeanRequest<HuoyuanFragment.StockAlldata, MamaHaoServerError> req = new BeanRequest<>(
                context,
                "",
                this,
                HuoyuanFragment.StockAlldata.class);

        req.setParam("apiCode", "_financial_001");
        req.setParam("userToken", MyApplication.getInstance().getUserToken());

        //获取token
        String token = NetworkManager.getInstance().getPostToken(req.getParam());
        req.setParam("token", token);

        baseActivity.addRequestQueue(req, REQUEST_STOCKS, new ReqTag.Builder().tag(REQUEST_TAG));

    }

    @Override
    protected void onResponseSuccess(ReqTag tag, Object data) {
        // TODO Auto-generated method stub
        super.onResponseSuccess(tag, data);
        if(!REQUEST_TAG.equals(tag.getTag()))
            return;

        switch (tag.getReqId()) {
            case REQUEST_GOODS_DATAS:
                //普通商品列表
                mPtrFrame.refreshComplete();
                handleDatas((List<CheyuanData>)data);
                break;
            case REQUEST_BANNER:
                setBanners((List<Banner>)data);
                break;
            case REQUEST_STOCKS:
                HuoyuanFragment.StockAlldata stockAlldata = (HuoyuanFragment.StockAlldata) data;
                List<StockData> nowStock = stockAlldata.list;
                if(nowStock!=null && nowStock.size()>0){
                    for(StockData stockData:nowStock){
                        if("IPBRNA0".equals(stockData.getSymbol())){
                            //布伦特连续
                            ((TextView)headerView.findViewById(R.id.tv_time1))
                                    .setText(stockData.getCreate_time());

                            TextView tv_price1 = ((TextView)headerView.findViewById(R.id.tv_price1));
                            TextView tv_change_ratio1 = ((TextView)headerView.findViewById(R.id.tv_change_ratio1));
                            TextView tv_change_ratio_rate1 = ((TextView)headerView.findViewById(R.id.tv_change_ratio_rate1));

                            tv_price1.setText(stockData.getNewprice());

                            if(stockData.getPricechangeratio().contains("-")){
                                //负的
                                tv_price1.setTextColor(Color.parseColor("#72AD46"));
                                tv_change_ratio1.setTextColor(Color.parseColor("#72AD46"));
                                tv_change_ratio_rate1.setTextColor(Color.parseColor("#72AD46"));

                                tv_change_ratio1.setText(CommonUtils.getNumFormat(stockData.getChangeRatio()));
                                tv_change_ratio_rate1.setText(CommonUtils.getNumFormat(stockData.getPricechangeratio())+"%");
                            }else{
                                tv_change_ratio1.setText("+"+CommonUtils.getNumFormat(stockData.getChangeRatio()));
                                tv_change_ratio_rate1.setText("+"+CommonUtils.getNumFormat(stockData.getPricechangeratio())+"%");
                            }//NECLA0
                        }else if("NECLA0".equals(stockData.getSymbol())){
                            //原油连续
                            ((TextView)headerView.findViewById(R.id.tv_time2))
                                    .setText(stockData.getCreate_time());

                            TextView tv_price2 = ((TextView)headerView.findViewById(R.id.tv_price2));
                            TextView tv_change_ratio2 = ((TextView)headerView.findViewById(R.id.tv_change_ratio2));
                            TextView tv_change_ratio_rate2 = ((TextView)headerView.findViewById(R.id.tv_change_ratio_rate2));

                            tv_price2.setText(stockData.getNewprice());

                            if(stockData.getPricechangeratio().contains("-")){
                                //负的
                                tv_price2.setTextColor(Color.parseColor("#72AD46"));
                                tv_change_ratio2.setTextColor(Color.parseColor("#72AD46"));
                                tv_change_ratio_rate2.setTextColor(Color.parseColor("#72AD46"));

                                tv_change_ratio2.setText(CommonUtils.getNumFormat(stockData.getChangeRatio()));
                                tv_change_ratio_rate2.setText(CommonUtils.getNumFormat(stockData.getPricechangeratio())+"%");
                            }else{
                                tv_change_ratio2.setText("+"+CommonUtils.getNumFormat(stockData.getChangeRatio()));
                                tv_change_ratio_rate2.setText("+"+CommonUtils.getNumFormat(stockData.getPricechangeratio())+"%");
                            }//
                        }else if("SEsc1812".equals(stockData.getSymbol())){
                            ((TextView)headerView.findViewById(R.id.tv_time3))
                                    .setText(stockData.getCreate_time());

                            TextView tv_price3 = ((TextView)headerView.findViewById(R.id.tv_price3));
                            TextView tv_change_ratio3 = ((TextView)headerView.findViewById(R.id.tv_change_ratio3));
                            TextView tv_change_ratio_rate3 = ((TextView)headerView.findViewById(R.id.tv_change_ratio_rate3));
                            tv_price3.setText(stockData.getNewprice());
                            if(stockData.getPricechangeratio().contains("-")){
                                //负的
                                tv_price3.setTextColor(Color.parseColor("#72AD46"));
                                tv_change_ratio3.setTextColor(Color.parseColor("#72AD46"));
                                tv_change_ratio_rate3.setTextColor(Color.parseColor("#72AD46"));

                                tv_change_ratio3.setText(CommonUtils.getNumFormat(stockData.getChangeRatio()));
                                tv_change_ratio_rate3.setText(CommonUtils.getNumFormat(stockData.getPricechangeratio())+"%");
                            }else{
                                tv_change_ratio3.setText("+"+CommonUtils.getNumFormat(stockData.getChangeRatio()));
                                tv_change_ratio_rate3.setText("+"+CommonUtils.getNumFormat(stockData.getPricechangeratio())+"%");
                            }
                        }
                    }
                }
                //原油收盘
                List<StockData> closeStock = stockAlldata.close;
                StringBuilder stringBuilder = new StringBuilder();
                if(closeStock!=null && closeStock.size()>0){
                    boolean isbltAdd = false;
                    boolean islianxuAdd = false;
                    boolean is1809Add = false;
                    stringBuilder.append(closeStock.get(0).getTime()).append("原油收盘:");
                    for(StockData stockData:closeStock){
                        if("IPBRNA0".equals(stockData.getSymbol())){
                            //布伦特连续
                            isbltAdd = !stockData.getChangepercent().contains("-");
                            stringBuilder.append("布伦特:").append(stockData.getLastclose()).append(isbltAdd?"↑":"↓").append(stockData.getChangepercent());
                        }else if("NECLA0".equals(stockData.getSymbol())){
                            //原油连续
                            islianxuAdd = !stockData.getChangepercent().contains("-");
                            stringBuilder.append("WTI:").append(stockData.getLastclose()).append(islianxuAdd?"↑":"↓").append(stockData.getChangepercent());
                        }else if("SEsc1812".equals(stockData.getSymbol())){
                            is1809Add = !stockData.getChangepercent().contains("-");
                            stringBuilder.append("原油1812:").append(stockData.getLastclose()).append(is1809Add?"↑":"↓").append(stockData.getChangepercent());
                        }
                        stringBuilder.append(",");
                    }

                    MarqueeView marqueeview_stock = headerView.findViewById(R.id.marqueeview_stock);
                    marqueeview_stock.setText(stringBuilder.substring(0,stringBuilder.length()-1));
                }
                break;

            default:
                break;
        }
    }

    @Override
    protected void onResponseFailure(ReqTag tag, MamaHaoServerError error,
                                     AbstractRequest.MamaHaoError clientError) {
        // TODO Auto-generated method stub
        super.onResponseFailure(tag, error, clientError);

        if(!REQUEST_TAG.equals(tag.getTag()))
            return;

        switch (tag.getReqId()) {
            case REQUEST_GOODS_DATAS:
                mPtrFrame.refreshComplete();
                //普通商品列表
                handleDatas(null);
                break;

            default:
                break;
        }
    }

    @Override
    protected void processClick(View v) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 101 && resultCode == Activity.RESULT_OK){
            refreshDatas(true,true);
        }
    }
}
